package com.kkb.merchant.center.controller;


import com.alibaba.druid.sql.visitor.functions.Char;
import com.csvreader.CsvWriter;
import com.github.pagehelper.PageInfo;
import com.kkb.merchant.center.api.CategoryInfoService;
import com.kkb.merchant.center.common.pojo.CategoryInfo;
import com.kkb.merchant.center.common.util.FileUtil;
import com.kkb.merchant.center.common.util.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "商城:商品分类管理")
@RestController
@RequestMapping("api")
public class CategoryController {

    @Reference
    private CategoryInfoService categoryInfoService;

    @ApiOperation(value = "获取全部商品分类")
    @GetMapping(value = "/queryCategory")
    public HttpResult queryAllCategory(Integer page, Integer size){
        List<CategoryInfo> categories = categoryInfoService.selectAllCategory();
        PageInfo<CategoryInfo> pageInfo=new PageInfo<>(categories);
        return HttpResult.success(pageInfo);
    }

    @ApiOperation(value = "获取前两级商品分类")
    @GetMapping(value = "/queryCategoryLevel2")
    public HttpResult queryCategoryLevel2(){
        List<CategoryInfo> categories = categoryInfoService.selectCategoryLevel2();
        return HttpResult.success(categories);
    }

    @GetMapping(value = "/createCategroyCsv")
    public HttpResult createCsv(){
        String filePath = "/Users/hadoop/Desktop/test2.csv";
        int result = 0;

        CsvWriter csvWriter = null;

        try {
            csvWriter = new CsvWriter(filePath,',', Charset.forName("utf-8"));
            String[] headers = {"id","分类名称","父ID","层级","顺序","状态"};
            csvWriter.writeRecord(headers);
            List<CategoryInfo> categoryInfos = categoryInfoService.selectAllCategory();
            for(CategoryInfo categoryInfo:categoryInfos){
                List<String> contentlist = new ArrayList<>();
                contentlist.add(String.valueOf(categoryInfo.getId()));
                contentlist.add(categoryInfo.getCategoryName());
                contentlist.add(String.valueOf(categoryInfo.getParentId()));
                contentlist.add(String.valueOf(categoryInfo.getLevel()));
                contentlist.add(String.valueOf(categoryInfo.getSort()));
                contentlist.add(String.valueOf(categoryInfo.getStatus()));

                String[] array = contentlist.toArray(new String[contentlist.size()]);
                csvWriter.writeRecord(array);
                result++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            csvWriter.close();
        }

        return HttpResult.success(result);

    }

    @GetMapping("/downloadCategroyCsv")
    public void downloadAllCategroy(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = "test2.csv";
        String realpath = "/Users/hadoop/Desktop";
        File file = new File(realpath,fileName);

        if(file.exists()){
            FileInputStream fis = null;
            BufferedInputStream bis = null;

            try {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();

                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }

                System.out.println("download the file success");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(bis!=null){
                    bis.close();
                }

                if(fis!=null){
                    fis.close();
                }
            }
        }
    }

    @PostMapping("/uploadFile")
    public HttpResult uploadFile(@RequestParam("file")MultipartFile multipartFile){
        String result = null;
        String directory = "/Users/hadoop/Desktop";

        try {
            File file = FileUtil.toFile(multipartFile,directory);
            boolean b = file.createNewFile();
            System.out.println(file.getName());
            result = file.getName();

        } catch (IOException e) {
            e.printStackTrace();
            result = "服务异常";
        }
        return HttpResult.success(result);
    }
}
